<?php

namespace app\admin\controller;

use app\model\GoodsCatModel;
use support\Request;
use support\Response;
use app\model\Util;

/**
 * 商品分类管理控制器
 * 
 * @package app\admin\controller
 */
class GoodsCatController
{
    /**
     * 获取分类列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $page = (int)$request->get('page', 1);
            $pageSize = (int)$request->get('pageSize', 10);

            $query = GoodsCatModel::query();

            // 获取所有分类，按层级和排序显示
            $categories = $query->orderBy('fid', 'asc')
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'asc')
                ->get();

            foreach($categories as &$item){
                $item['image_url'] = Util::pathToUrl($item->image);
            }    

            // 构建树形结构
            $tree = $this->buildCategoryTree($categories);

            return json([
                'data' => [
                    'list' => $tree,
                    'total' => count($categories)
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 添加分类
     * 
     * @param Request $request
     * @return Response
     */
    public function store(Request $request): Response
    {
        try {
            $name = $request->post('name');
            $fid = (int)$request->post('parent_id', 0);
            $sort = (int)$request->post('sort', 0);
            $url = $request->post('url', null);

            // 参数验证
            if (empty($name)) {
                throw new \Exception('分类名称不能为空');
            }

            // 检查父分类是否存在
            if ($fid > 0) {
                $parentCategory = GoodsCatModel::find($fid);
                if (!$parentCategory) {
                    throw new \Exception('父分类不存在');
                }

                // 检查是否已经是二级分类
                if ($parentCategory->fid > 0) {
                    throw new \Exception('不支持三级分类');
                }
            }

            // 检查同级分类名称是否重复
            $existingCategory = GoodsCatModel::where('name', $name)
                ->where('fid', $fid)
                ->first();
            if ($existingCategory) {
                throw new \Exception('同级分类名称已存在');
            }

            $image = $request->post('image');

            // 创建分类
            $category = new GoodsCatModel();
            $category->name = $name;
            $category->fid = $fid;
            $category->sort = $sort;
            $category->image = $image;
            $category->url = $url;
            $category->created_at = time();
            $category->updated_at = time();
            $category->save();

            return json([
                'data' => $category,
                'msg' => '添加成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新分类
     */
    public function update(Request $request): Response
    {
        try {
            $id = (int)$request->post('id');
            $name = $request->post('name');
            $fid = (int)$request->post('parent_id', 0);
            $sort = (int)$request->post('sort', 0);
            $url = $request->post('url', null);
            if (empty($id)) {
                throw new \Exception('分类ID不能为空');
            }

            if (empty($name)) {
                throw new \Exception('分类名称不能为空');
            }

            $category = GoodsCatModel::find($id);
            if (!$category) {
                throw new \Exception('分类不存在');
            }

            // 检查父分类是否存在
            if ($fid > 0) {
                $parentCategory = GoodsCatModel::find($fid);
                if (!$parentCategory) {
                    throw new \Exception('父分类不存在');
                }

                // 检查是否已经是二级分类
                if ($parentCategory->fid > 0) {
                    throw new \Exception('不支持三级分类');
                }

                // 检查是否将分类设置为自己的子分类
                if ($fid == $id) {
                    throw new \Exception('不能将分类设置为自己的子分类');
                }
            }

            // 检查同级分类名称是否重复（排除自己）
            $existingCategory = GoodsCatModel::where('name', $name)
                ->where('fid', $fid)
                ->where('id', '!=', $id)
                ->first();
            if ($existingCategory) {
                throw new \Exception('同级分类名称已存在');
            }

            $image = $request->post('image');

            // 更新分类
            $category->name = $name;
            $category->fid = $fid;
            $category->sort = $sort;
            $category->image = $image;
            $category->url = $url;
            $category->updated_at = time();
            $category->save();

            return json([
                'data' => $category,
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除分类
     */
    public function del(Request $request): Response
    {
        try {
            $id = (int)$request->post('id');

            if (empty($id)) {
                throw new \Exception('分类ID不能为空');
            }

            $category = GoodsCatModel::find($id);
            if (!$category) {
                throw new \Exception('分类不存在');
            }

            // 检查是否有子分类
            $childCount = GoodsCatModel::where('fid', $id)->count();
            if ($childCount > 0) {
                throw new \Exception('该分类下有子分类，无法删除');
            }

            $category->delete();

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 构建分类树形结构
     * 
     * @param array $categories
     * @return array
     */
    private function buildCategoryTree($categories): array
    {
        $tree = [];
        $map = [];

        // 创建映射
        foreach ($categories as $category) {
            $map[$category->id] = $category->toArray();
            $map[$category->id]['children'] = [];
            $map[$category->id]['hasChildren'] = false;
        }

        // 构建树形结构
        foreach ($map as $id => $category) {
            if ($category['fid'] == 0) {
                $tree[] = &$map[$id];
            } else {
                if (isset($map[$category['fid']])) {
                    $map[$category['fid']]['children'][] = &$map[$id];
                    $map[$category['fid']]['hasChildren'] = true;
                }
            }
        }

        // 按排序字段排序
        $this->sortTree($tree);

        return $tree;
    }

    /**
     * 递归排序树形结构
     * 
     * @param array $tree
     */
    private function sortTree(&$tree): void
    {
        // 按sort字段排序
        usort($tree, function ($a, $b) {
            return $a['sort'] - $b['sort'];
        });

        // 递归排序子节点
        foreach ($tree as &$item) {
            if (!empty($item['children'])) {
                $this->sortTree($item['children']);
            }
        }
    }
}
